<?php


namespace app\controller\admin\partner;


use app\common\exception\ApiException;
use app\common\RedisKey;
use app\controller\admin\BaseAdminController;
use app\facade\RedisLocationFacade;
use app\model\config\CancelReasonModel;
use app\model\config\RegionModel;
use app\model\goods\OrderModel;
use app\model\partner\EscortMenuModel;
use app\model\partner\EscortMenuOrderLogModel;
use app\model\partner\EscortMenuOrderModel;
use app\model\partner\EscortMenuReserveOrderModel;
use app\model\partner\OrderLogModel;
use app\model\partner\UserPartnerModel;
use app\model\user\PartnerMoneyRecordModel;
use app\model\user\UserModel;
use app\service\config\ConfigService;
use app\service\config\DutyService;
use app\service\order\PartnerOrderService;
use app\service\order\VerifyOrderService;
use app\service\utils\GenerateUserNickService;
use app\service\utils\LockService;
use app\service\utils\QqMapService;
use think\facade\Db;
use think\facade\Queue;

class ReserveOrderController extends BaseAdminController
{

    function setModel()
    {
        return new EscortMenuReserveOrderModel();
    }

    function setWithModel()
    {
        return ['user', 'partner', 'source', 'city', 'menuOrder'];
    }

    function setSearch()
    {
        $where = [];
        $status = $this->request->param('status', 0);
        if (!$status) {
            $where[] = ['EscortMenuReserveOrderModel.status', '<>', 6];
        }
        return [
            '=' => ['source_id', 'status', 'coach_user_id', 'order_type'],
            'like' => ['order_sn', 'user.mobile' => 'user_mobile', 'mobile', 'city_id'],
            'betweenTimestamp' => ['reserve_time', 'create_time'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function getList()
    {
        try {
            $list = parent::getList()->toArray();
            foreach ($list['data'] as &$item) {
                if ($item['order_type'] == 1) {
                    $item['service_num'] = EscortMenuReserveOrderModel::where('user_id', $item['user_id'])
                        ->whereIn('status', [1, 2, 3, 4, 5, 7, 8])
                        ->count();
                    $item['reserve_date'] = date('Y-m-d', $item['reserve_time']);
                    $item['reserve_start'] = date('H:i', $item['reserve_time']);
                    $item['reserve_end'] = date('H:i', $item['reserve_time'] + $item['duration'] * 3600);

                    if ($item['status'] != 5) {

                        if ($item['is_trial'] == 1) {
                            $amount = $item['partner_trial_class_amount'] ?? 0;
                            $item['partner_fee_prefix'] = "$amount * {$item['duration']} = ";
                            $item['partner_fee'] = bcmul($amount, $item['duration'], 1);
                        } else {
                            $amount = $item['partner_class_amount'] ?? 0;
                            $item['partner_fee_prefix'] = "$amount * {$item['duration']} = ";
                            $item['partner_fee'] = bcmul($amount, $item['duration'], 1);
                        }
                    } else {
                        $item['partner_fee_prefix'] = '';
                        $item['partner_fee'] = PartnerMoneyRecordModel::where('user_id', $item['coach_user_id'])
                            ->where('order_sn', $item['order_sn'])
                            ->value('amount');
                    }
                }
//                $remarkList = OrderLogModel::where('order_id', $item['id'])->column('reason');
//                $item['remark'] = $item['remark'] . implode(';', $remarkList);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 添加订单
     * @return \think\response\Json
     */
    public function save()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0);
            $data = $this->request->only(['source_id', 'city_id', 'address', 'coach_user_id', 'reserve_time',
                'lng', 'lat', 'duration', 'mobile', 'username', 'remark', 'is_trial'], 'param', 'trim');
            if (!isset($data['city_id']) || !$data['city_id']) {
                throw new ApiException('请选择城市');
            }
            if (!isset($data['address']) || !$data['address']) {
                throw new ApiException('请选择地址');
            }
            if (!isset($data['mobile']) || !$data['mobile']) {
                throw new ApiException('请填写用户手机号');
            }

            if (!isset($data['reserve_time'])) {
                throw new ApiException('请选择预约时间');
            }
            $coachUserId = $data['coach_user_id'] ?? 0;
            $data['reserve_time'] = strtotime($data['reserve_time']);

            $fullAddress = RegionModel::where('id', $data['city_id'])->value('name') . $data['address'];
            $qqMapService = new QqMapService();
            $res = $qqMapService->getCoordinate($fullAddress);
            $lng = $res['lng'];
            $lat = $res['lat'];

            $userId = UserModel::where('mobile', $data['mobile'])->value('id', 0);
            if (!$userId) {
                $userModel = new UserModel();
                $userModel->mobile = $data['mobile'];
                $userModel->username = $data['username'];
                $userModel->city_id = $data['city_id'];
                $userModel->save();
                $userId = $userModel->id;
            }
            $data['user_id'] = $userId;

            if (!$id) {
                $orderInfo = EscortMenuReserveOrderModel::where('user_id', $userId)
                    ->where('is_trial', 1)
                    ->where('order_type', 1)
                    ->where('status', '<>', 6)
                    ->find();
                if ($orderInfo) {
                    throw new ApiException('该号码已经使用过体验课');
                }
                $data['order_sn'] = createOrderSn('escort_menu_reserve_order', 'order_sn', 'HPJ');

                // 生成一个套餐订单
                $escortMenuOrderModel = new EscortMenuOrderModel();
                $escortMenuOrderModel->user_id = $data['user_id'];
                $escortMenuOrderModel->order_sn = $data['order_sn'];
                $escortMenuOrderModel->pay_status = 3;
                $escortMenuOrderModel->total = $data['duration'];
                $escortMenuOrderModel->min = $data['is_trial'] == 1 ? $data['duration'] : 2;
                $escortMenuOrderModel->city_id = [$data['city_id']];
                $escortMenuOrderModel->valid_time = time() + 90 * 86400;
                $escortMenuOrderModel->used_duration = $data['duration'];
                $escortMenuOrderModel->residue_duration = 0;
                $escortMenuOrderModel->is_trial = $data['is_trial'];
                $escortMenuOrderModel->menu_name = $data['is_trial'] == 1 ? $data['duration'] . '小时体验课' : $data['duration'] . '小时正式课';
                $escortMenuOrderModel->menu_image = ConfigService::getConfigValue('goods_img');
                $escortMenuOrderModel->source_id = $data['source_id'];
                $escortMenuOrderModel->save();

                // 订单中心
                $orderModel = new OrderModel();
                $orderModel->order_sn = $data['order_sn'];
                $orderModel->order_type = 0;
                $orderModel->user_id = $data['user_id'];
                $orderModel->city_id = $data['city_id'];
                $orderModel->mobile = $data['mobile'];
                $orderModel->reserve_time = $data['reserve_time'];
                $orderModel->save();

                // 套餐使用日志
                $escortMenuOrderLogModel = new EscortMenuOrderLogModel();
                $escortMenuOrderLogModel->order_sn = $escortMenuOrderModel->order_sn;
                $escortMenuOrderLogModel->total = $escortMenuOrderModel->total;
                $escortMenuOrderLogModel->used_duration = $escortMenuOrderModel->used_duration;
                $escortMenuOrderLogModel->residue_duration = $escortMenuOrderModel->residue_duration;
                $escortMenuOrderLogModel->coach_id = $userId;
                $escortMenuOrderLogModel->remark = '后台添加预约订单';
                $escortMenuOrderLogModel->save();

                // 预约订单
                $id = $escortMenuOrderModel->id;
                $escortMenuReserveOrderModel = new EscortMenuReserveOrderModel();
                $data['order_type'] = 1;
                $data['order_id'] = $id;
                $data['reserve_type'] = $coachUserId > 0 ? 2 : 1;
                $data['status'] = $coachUserId > 0 ? 3 : 2;
                $data['lng'] = $lng;
                $data['lat'] = $lat;
                $escortMenuReserveOrderModel->save($data);

                // 订单日志
                $orderLogModel = new OrderLogModel();
                $orderLogModel->order_id = $id;
                $orderLogModel->admin_id = $userId;
                $orderLogModel->title = '后台添加预约订单';
                $orderLogModel->reason = '教练ID：' . $coachUserId;
                $orderLogModel->save();

                if ($coachUserId) {
                    // 新订单通知
                    Queue::push('WeiXinTemplateMsgJob', ['msg_type' => 'new_order', 'id' => $escortMenuReserveOrderModel->id]);
                }
            } else {
                $partnerOrderModel = $this->setModel()->find($id);
                $oldCoachUid = $partnerOrderModel['coach_user_id'];
                $data['lng'] = $lng;
                $data['lat'] = $lat;
                $partnerOrderModel->save($data);

                // 订单日志
                $orderLogModel = new OrderLogModel();
                $orderLogModel->order_id = $id;
                $orderLogModel->admin_id = $userId;
                $orderLogModel->title = '后台编辑预约订单';
                $orderLogModel->reason = "教练ID：$coachUserId,原教练ID：$oldCoachUid";
                $orderLogModel->save();

                if ($oldCoachUid && $oldCoachUid != $coachUserId) {
                    DutyService::cancelBusyTime($coachUserId, $data['reserve_time'], $data['duration']);
                }
            }

            if ($coachUserId > 0) {
                // 教练排班
                DutyService::setBusyTime($coachUserId, $data['reserve_time'], $data['duration'], $id);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 创建验车订单
     * @return \think\response\Json
     */
    public function createVerifyOrder()
    {
        try {
            $id = $this->request->param('id', 0);
            $data = $this->request->only(['source_id', 'city_id', 'address', 'reserve_time', 'lng', 'lat',
                'condition', 'brand', 'cart_type', 'username', 'remark', 'mobile', 'menu_id'], 'param', 'trim');
            if (!isset($data['city_id']) || !$data['city_id']) {
                throw new ApiException('请选择城市');
            }
            if (!isset($data['address']) || !$data['address']) {
                throw new ApiException('请选择地址');
            }
            if (!isset($data['mobile']) || !$data['mobile']) {
                throw new ApiException('请填写用户手机号');
            }
            if (!isset($data['menu_id']) || !$data['menu_id']) {
                throw new ApiException('请选择套餐');
            }
            $menuInfo = EscortMenuModel::find($data['menu_id']);
            if (!$menuInfo) {
                throw new ApiException('套餐不存在');
            }
            if (!isset($data['reserve_time'])) {
                throw new ApiException('请选择预约时间');
            }

            $data['reserve_time'] = strtotime($data['reserve_time']);

            $userId = UserModel::where('mobile', $data['mobile'])->value('id', 0);
            if (!$userId) {
                $userModel = new UserModel();
                $userModel->mobile = $data['mobile'];
                $userModel->username = $data['username'];
                $userModel->city_id = $data['city_id'];
                $userModel->save();
                $userId = $userModel->id;
            }
            $data['user_id'] = $userId;
            $fullAddress = RegionModel::where('id', $data['city_id'])->value('name') . $data['address'];
            $qqMapService = new QqMapService();
            $res = $qqMapService->getCoordinate($fullAddress);
            $lng = $res['lng'];
            $lat = $res['lat'];

            if (!$id) {
                $data['order_sn'] = createOrderSn('escort_menu_reserve_order', 'order_sn', 'HYC');

                // 生成一个套餐订单
                $escortMenuOrderModel = new EscortMenuOrderModel();
                $escortMenuOrderModel->order_type = 2;
                $escortMenuOrderModel->user_id = $data['user_id'];
                $escortMenuOrderModel->order_sn = $data['order_sn'];
                $escortMenuOrderModel->pay_status = 2;
                $escortMenuOrderModel->city_id = $data['city_id'] ?? 0;
                $escortMenuOrderModel->valid_time = time() + 90 * 86400;
                $escortMenuOrderModel->menu_price = $menuInfo['price'];
                $escortMenuOrderModel->menu_old_price = $menuInfo['old_price'];
                $escortMenuOrderModel->menu_name = $menuInfo['name'];
                $escortMenuOrderModel->menu_image = $menuInfo['image'];
                $escortMenuOrderModel->menu_id = $menuInfo['id'];
                $escortMenuOrderModel->source_id = $data['source_id'];
                $escortMenuOrderModel->amount = $menuInfo['price'];
                $escortMenuOrderModel->pay_amount = $menuInfo['price'];
                $escortMenuOrderModel->coach_amount = $menuInfo['amount'];
                $escortMenuOrderModel->save();

                // 订单中心
                $orderModel = new OrderModel();
                $orderModel->order_sn = $data['order_sn'];
                $orderModel->order_type = 1;
                $orderModel->user_id = $data['user_id'];
                $orderModel->city_id = $data['city_id'] ?? 0;
                $orderModel->mobile = $data['mobile'];
                $orderModel->reserve_time = $data['reserve_time'];
                $orderModel->save();

                // 预约订单
                $escortMenuReserveOrderModel = new EscortMenuReserveOrderModel();
                $data['order_type'] = 2;
                $data['order_id'] = $escortMenuOrderModel->id;
                $data['reserve_type'] = 1;
                $data['status'] = EscortMenuReserveOrderModel::WAIT_ASSIGN_ORDER;
                $data['lng'] = $lng;
                $data['lat'] = $lat;
                $escortMenuReserveOrderModel->save($data);

                if (!isset($data['coach_user_id'])) {
                    // 新订单通知
                    Queue::push('WeiXinTemplateMsgJob', ['msg_type' => 'new_order', 'id' => $escortMenuReserveOrderModel->id]);
                }
            } else {
                $partnerOrderModel = $this->setModel()->find($id);
                $data['lng'] = $lng;
                $data['lat'] = $lat;
                $partnerOrderModel->save($data);

                $escortMenuOrderModel = EscortMenuOrderModel::where('order_sn', $partnerOrderModel['order_sn'])->find();
                $escortMenuOrderModel->user_id = $data['user_id'];
                $escortMenuOrderModel->city_id = $data['city_id'] ?? 0;
                $escortMenuOrderModel->valid_time = time() + 90 * 86400;
                $escortMenuOrderModel->menu_price = $menuInfo['price'];
                $escortMenuOrderModel->menu_old_price = $menuInfo['old_price'];
                $escortMenuOrderModel->menu_name = $menuInfo['name'];
                $escortMenuOrderModel->menu_image = $menuInfo['image'];
                $escortMenuOrderModel->menu_id = $menuInfo['id'];
                $escortMenuOrderModel->source_id = $data['source_id'];
                $escortMenuOrderModel->amount = $menuInfo['price'];
                $escortMenuOrderModel->pay_amount = $menuInfo['price'];
                $escortMenuOrderModel->coach_amount = $menuInfo['amount'];
                $escortMenuOrderModel->save();
            }

            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 派单
     * @return \think\response\Json
     */
    public function setCoach()
    {
        Db::startTrans();
        try {
            $userId = $this->request->middleware('userId');
            $id = $this->request->param('id', 0);
            $coachId = $this->request->param('coach_id', '', 'trim');

            $orderInfo = $this->setModel()->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }

            if ($orderInfo['coach_user_id']) {
                // 教练取消排班
                DutyService::cancelBusyTime($orderInfo['coach_user_id'], $orderInfo['reserve_time'], $orderInfo['duration']);
            }

            $orderInfo->coach_user_id = $coachId;
            $orderInfo->status = EscortMenuReserveOrderModel::WAIT_SERVICE;
            $orderInfo->save();

            // 订单日志 后台放入大厅
            $orderLogModel = new OrderLogModel();
            $orderLogModel->order_id = $id;
            $orderLogModel->admin_id = $userId;
            $orderLogModel->title = '订单派单给教练：' . $coachId;
            $orderLogModel->reason = '';
            $orderLogModel->save();

            // 教练排班
            DutyService::setBusyTime($coachId, $orderInfo['reserve_time'], $orderInfo['duration'], $id);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 放置大厅
     * @return \think\response\Json
     */
    public function toPublic()
    {
        Db::startTrans();
        try {
            $userId = $this->request->middleware('userId');
            $id = $this->request->param('id', 0);
            $remark = $this->request->param('remark', 0);

            $orderInfo = $this->setModel()->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            $orderInfo->status = EscortMenuReserveOrderModel::WAIT_ASSIGN_ORDER;
            $orderInfo->coach_user_id = 0;
            $orderInfo->accept_time = 0;
            $orderInfo->remark = $remark;
            $orderInfo->save();

//            if ($orderInfo['coach_user_id']) {
//                $coachUserInfo = UserPartnerModel::find($orderInfo['coach_user_id']);
//                $coachUserInfo->service_num = Db::raw('service_num-1');
//                $coachUserInfo->save();
//            }

            // 订单日志 后台放入大厅
            $orderLogModel = new OrderLogModel();
            $orderLogModel->order_id = $id;
            $orderLogModel->admin_id = $userId;
            $orderLogModel->type = 5;
            $orderLogModel->title = '放入大厅';
            $orderLogModel->reason = $remark;
            $orderLogModel->save();

            // 教练排班
            DutyService::cancelBusyTime($orderInfo['coach_user_id'], $orderInfo['reserve_time'], $orderInfo['duration']);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 上传凭证
     * @return \think\response\Json
     */
    public function uploadVoucher()
    {
        try {
            $id = $this->request->param('order_id', 0);
            $code = $this->request->param('coupon_code', '', 'trim');
            $img = $this->request->param('coupon_code_img', '', 'trim');
            $payAmount = $this->request->param('pay_amount', '', 'trim');
            $coachAmount = $this->request->param('coach_amount', '', 'trim');

            $orderInfo = $this->setModel()->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            $orderInfo->coupon_code = $code;
            $orderInfo->coupon_code_img = $img;
            $orderInfo->status = EscortMenuReserveOrderModel::WAIT_CHECK_COUPON;
            $orderInfo->save();

            if ($coachAmount > 0) {
                $menuOrderInfo = EscortMenuOrderModel::find($orderInfo['order_id']);
                if (!$menuOrderInfo) {
                    throw new ApiException('套餐订单不存在');
                }
                $menuOrderInfo->pay_amount = $payAmount;
                $menuOrderInfo->menu_price = $payAmount;
                $menuOrderInfo->menu_old_price = $payAmount;
                $menuOrderInfo->coach_amount = $coachAmount;
                $menuOrderInfo->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 验券
     * @return \think\response\Json
     */
    public function checkCoupon()
    {
        Db::startTrans();
        $orderId = $this->request->param('id', 0, 'int');
        $key = sprintf("complete:verify_car:%d", $orderId);
        $lockService = new LockService($key);
        $uniqid = uniqid();
        try {
            if (!$lockService->acquireLockWithoutRetry($uniqid)) {
                throw new ApiException('请勿重复完成');
            }
            $status = $this->request->param('status', 0);
            $coachAmount = $this->request->param('coach_amount', 0);
            $orderInfo = $this->setModel()->find($orderId);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            if ($status == 1) {
                // 结算工资
                if ($orderInfo['order_type'] == 1) {
                    $partnerOrderService = new PartnerOrderService();
                    $partnerOrderService->completeOrderService($orderId);
                } else {
                    VerifyOrderService::completeOrderService($orderId, $coachAmount);
                }
            } else {
                $orderInfo->status = EscortMenuReserveOrderModel::WAIT_UPLOAD;
                $orderInfo->save();
            }
            Db::commit();
            $lockService->releaseLock($uniqid);
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            $lockService->releaseLock($uniqid);
            return $this->error($exception);
        }
    }


    /**
     * 订单状态
     * @return \think\response\Json
     */
    public function getArr()
    {
        try {
            $arr = $this->setModel()->getStatusArr();
            return $this->success($arr);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 取消订单
     * @return \think\response\Json
     */
    public function cancel()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0);
            $remark = $this->request->param('remark', '');

            $orderInfo = $this->setModel()->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            if ($orderInfo['status'] == 4) {
                throw new ApiException('订单已完成，不能取消');
            }
            if ($orderInfo['status'] == 5) {
                throw new ApiException('订单已完成，不能取消');
            }
            $orderInfo->status = EscortMenuReserveOrderModel::CANCEL;
            $orderInfo->remark = $remark;
            $orderInfo->save();

            // 返回套餐时长
            if ($orderInfo['source_id'] == 1) {
                $escortMenuOrderModel = EscortMenuOrderModel::find($orderInfo['order_id']);
                $escortMenuOrderModel->used_duration = Db::raw("used_duration-{$orderInfo['duration']}");
                $escortMenuOrderModel->residue_duration = Db::raw("residue_duration+{$orderInfo['duration']}");
                $escortMenuOrderModel->pay_status = 2;
                $escortMenuOrderModel->save();
            } else {
                $escortMenuOrderModel = EscortMenuOrderModel::find($orderInfo['order_id']);
                $escortMenuOrderModel->pay_status = 4;
                $escortMenuOrderModel->save();
            }

//            if ($orderInfo['coach_user_id']) {
//                $coachUserInfo = UserPartnerModel::find($orderInfo['coach_user_id']);
//                $coachUserInfo->service_num = Db::raw('service_num-1');
//                $coachUserInfo->save();
//            }
            $userId = $this->request->middleware('userId');

            // 订单日志 后台取消订单
            $orderLogModel = new OrderLogModel();
            $orderLogModel->order_id = $id;
            $orderLogModel->admin_id = $userId;
            $orderLogModel->type = 4;
            $orderLogModel->title = '取消订单';
            $orderLogModel->reason = $remark;
            $orderLogModel->save();

            // 订单中心
            $orderCenter = OrderModel::where('order_sn', $orderInfo['order_sn'])->find();
            if ($orderCenter) {
                $orderCenter->order_status = -1;
                $orderCenter->save();
            }

            // 教练排班
            DutyService::cancelBusyTime($orderInfo['coach_user_id'], $orderInfo['reserve_time'], $orderInfo['duration']);

            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 附近教练列表
     * @return \think\response\Json
     */
    public function getNearPartnerList()
    {
        try {
            $id = $this->request->param('id', 0);
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $mobile = $this->request->param('mobile', '', 'trim');
            $username = $this->request->param('username', '', 'trim');
            $orderInfo = $this->setModel()->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            $orderType = $orderInfo['order_type'];
            if ($orderType == 1) {
                // 陪驾
                $where[] = ['user_type', 'in', [0, 2]];
            } else {
                // 验车
                $where[] = ['user_type', 'in', [1, 2]];
            }
            $distance = 50000;
            if (!$mobile && !$username) {
                $where[] = ['city', '=', $orderInfo['city_id']];
                $distance = 50;
            }

            $where[] = ['status', '=', 1];
            $where[] = ['is_forbid', '=', 0];
            if ($mobile != '') {
                $where[] = ['mobile', 'like', "%{$mobile}%"];
            }
            if ($username != '') {
                $where[] = ['username', 'like', "%{$username}%"];
            }
            $locationArr = RedisLocationFacade::getMembersByDistance(RedisKey::PARTNER_LOCATION_LIST, $orderInfo['lng'], $orderInfo['lat'], $distance);
//            var_dump($locationArr);
            if (!$locationArr) {
                return $this->success();
            }
            $locationArr = RedisLocationFacade::formatLocation($locationArr);
            $partnerIdArr = $locationArr['key'];
            $distanceArr = $locationArr['value'];
            $partnerIdStr = implode(',', $partnerIdArr);

            $where[] = ['id', 'in', $partnerIdArr];
//            var_dump($where);
            $list = UserPartnerModel::field('id,mobile,username')
                ->where($where)
                ->orderRaw("field(id,$partnerIdStr)")
                ->paginate(['list_row' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as $key => &$value) {
                $value['distance'] = number_format($distanceArr[$value['id']], 1) . 'km';
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 取消原因列表
     * @return \think\response\Json
     */
    public function getReasonList()
    {
        try {
            $type = $this->request->param('type', 0, 'int');
            $list = CancelReasonModel::where('type', $type)->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

}